package kokonut.shop;

import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kokonut.shop.product.Image;
import kokonut.shop.product.TShirtModel;
import persistence.ProductPersistence;

/**
 *
 * @author markel
 */
public class changeImageServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        String color = req.getParameter("color");
        int ref = Integer.parseInt(req.getParameter("ref"));
        String imageKey = "";
        if(color != null){
            //Create the product persistence object to make a consult
            ProductPersistence persistence = new ProductPersistence();
            //Load the TShirt model using its reference
            TShirtModel model = (TShirtModel)persistence.loadModelByRef(ref);
            //Find in the TShirt object the image of the needed color
            for(Image image :model.getModelImages()){
                if(image.getDescription().equals(color)){
                    imageKey = image.getImageKey();
                    break;
                }
            }

            resp.setContentType("text/plain");
            resp.setHeader("Cache-Control", "no-cache");
            resp.getWriter().write(imageKey);
        } else {
            //nothing to show
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    }

}
